package com.iseastar.guojiang.mine;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.iseastar.SplashActivity;
import com.iseastar.guojiang.BaseFragment;
import com.iseastar.guojiang.MainActivity;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.app.TimerService;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.CourierCenterDataBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.SettingBean;
import com.iseastar.guojiang.model.UserBean;
import com.iseastar.guojiang.newcabinet.CourierQRCodeActivity;
import com.iseastar.guojiang.newcabinet.ServicePointActivity;
import com.iseastar.guojiang.performance.MyPerformanceActivity;
import com.iseastar.guojiang.print.BluetoothSettingActivity;
import com.iseastar.guojiang.task.TaskHistoryActivity;
import com.iseastar.guojiang.team.CourierTeamCenterActivity;
import com.iseastar.guojiang.team.CreateCourierTeamActivity;
import com.iseastar.guojiang.transfer.TaskSatelliteWarehouseActivity;
import com.iseastar.guojiang.util.PollingUtils;
import com.iseastar.guojiang.wallet.MyWalletActivity;
import com.shouhuobao.station.R;

import java.io.ByteArrayOutputStream;

import droid.frame.Config;
import droid.frame.activity.ActivityMgr;
import droid.frame.app.Callback;
import droid.frame.push.PushInterface;
import droid.frame.utils.android.DataCleanManager;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.ObjectSerialize;

/**
 * 主界面tab3 个人中心
 *
 * @author coffee <br>
 * 2016-8-18上午10:39:38
 */
public class SettingFragment extends BaseFragment implements OnClickListener {

    private ImageView mUserPhoto;// 头像
    private TextView mUserName; // 用户名

    private Drawable mArrowRight;
    private Handler mhandler;
    private boolean isRequestGet = true;
    //
    private SettingBean setting;
    private CourierCenterDataBean bean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mhandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                isRequestGet = true;//
            }
        };
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.setting);
        super.findViewById();
        //        getAppTitle().setTitle(null, new TitleRes("个人中心"), new TitleRes(R.drawable.person_shezhi, new OnClickListener() {
        //            @Override
        //            public void onClick(View v) {
        //                startActivity(MySettingActivity.class);
        //            }
        //        }));
        //
        mUserPhoto = (ImageView) findViewById(R.id.user_photo);
        mUserName = (TextView) findViewById(R.id.user_name);
        //
        // findViewById(R.id.setting_order_list).setOnClickListener(this);
        //退出登录
        findViewById(R.id.setting_clear_data).setOnClickListener(this);
        //我的业绩
        findViewById(R.id.myenterprise_TV).setOnClickListener(this);
        //我的打印机
        findViewById(R.id.myprint_TV).setOnClickListener(this);
        //揽收任务
        findViewById(R.id.take_task_tv).setOnClickListener(this);
        //我的二维码
        findViewById(R.id.my_qr_code_tv).setOnClickListener(this);
        //历史任务
        findViewById(R.id.history_task_TV).setOnClickListener(this);
        //我的钱包
        findViewById(R.id.my_wallet_ll).setOnClickListener(this);
        //卫星仓
        findViewById(R.id.satellite_warehouse_tv).setOnClickListener(this);
        //切换至火箭联盟
        findViewById(R.id.switch_take).setOnClickListener(this);
        //战队中心
        findViewById(R.id.team_center_tv).setOnClickListener(this);
        //
        mArrowRight = getResources().getDrawable(R.drawable.app_arrow_right);
        mArrowRight.setBounds(0, 0, mArrowRight.getMinimumWidth(), mArrowRight.getMinimumHeight());
        // 初始化数据
        initViewData();
    }

    private void initViewData() {
        final UserBean user = AppCache.getUser();
        this.mUserName.setText(user.getNickName() + "  (" + user.getName() + "）");
        // 头像
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                // 头像
                Bitmap image = BitmapUtils.loadBitmapFromNet(user.getImagePath());
                return image;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                try {
                    if (result != null) {
                        result = imageZoom(result);
                        mUserPhoto.setImageBitmap(result);
                    }
                } catch (Error e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.execute();
    }

    private Bitmap imageZoom(Bitmap bitMap) {
        // 图片允许最大空间 单位：KB
        double maxSize = 100.00;
        // 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        // 将字节换成KB
        double mid = b.length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            // 获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
            // 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i), bitMap.getHeight() / Math.sqrt(i));
        }
        return bitMap;
    }

    /***
     * 图片的缩放方法
     *
     * @param bgimage
     *            ：源图片资源
     * @param newWidth
     *            ：缩放后宽度
     * @param newHeight
     *            ：缩放后高度
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            case MsgID.setting_info:
                cancelLoadingDialog();
                final ReqResult<SettingBean> result = JSON.parser(msg.obj, SettingBean.class);
                if (checkLoginStatus(result)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initViewData();// update 头像
                            handleSettingInfo(result);
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            //获取个人中心数据
            case MsgID.courier_get_center_data:
                final ReqResult<CourierCenterDataBean> reqResult = JSON.parser(msg.obj, CourierCenterDataBean.class);
                if (checkLoginStatus(reqResult)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            bean = reqResult.getResult();
                            if (bean != null) {
                                ((TextView) findViewById(R.id.person_money_tv)).setText("余额：" + bean.getMoney() + "元");
                                ((TextView) findViewById(R.id.week_count_tv)).setText(bean.getWeekCount());
                                ((TextView) findViewById(R.id.month_count_tv)).setText(bean.getMonthCount());
                                ((TextView) findViewById(R.id.total_count_tv)).setText(bean.getTotalCount());
                                if (bean.getWareHouseAdmin() == 1) {
                                    findViewById(R.id.satellite_warehouse_tv).setVisibility(View.VISIBLE);
                                } else {
                                    findViewById(R.id.satellite_warehouse_tv).setVisibility(View.GONE);
                                }
                            }
                        }
                    });
                } else {
                    showToast(reqResult.getMessage());
                }
                return true;
            //切换至火箭联盟
            case MsgID.switch_take:
                cancelLoadingDialog();
                final ReqResult<UserBean> userResult = JSON.parser(msg.obj, UserBean.class);
                //未开通驿站
                getActivityContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (userResult.getStatus() == 3002) {
                            DialogMgr.switchTake(SettingFragment.this);
                        } else if (checkLoginStatus(userResult) || userResult.getStatus() == 3003) {
                            MainActivity.instance.startOrStopRefreshLocation(false);
                            MainActivity.instance.setCouirerReceiveOrderStatus();
                            try {
                                PushInterface.logout();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            // 清空信息
                            AppCache.setUser(null);
                            AppCache.setOrder(null);
                            AppCache.setStationOpenInfoBean(null);
                            UserBean bean = userResult.getResult();
                            AppCache.setUser(bean);
                            Intent intent = new Intent();
                            intent.setClass(getActivityContext(), com.shouhuobao.take.MainActivity.class);
                            startActivity(intent);
                            for (Activity activity : ActivityMgr.getAllActivitys()) {
                                if (!(activity instanceof com.shouhuobao.take.MainActivity)) {
                                    activity.finish();
                                }
                            }
                            Intents.startLauncherActivity(getActivityContext());
                        } else {
                            showToast(userResult.getMessage());
                        }
                    }
                });
                return true;
            //注册火箭联盟账号
            case MsgID.open_the_station:
                cancelLoadingDialog();
                final ReqResult<UserBean> stationResult = JSON.parser(msg.obj, UserBean.class);
                if (checkLoginStatus(stationResult)) {
                    MainActivity.instance.startOrStopRefreshLocation(false);
                    MainActivity.instance.setCouirerReceiveOrderStatus();
                    PollingUtils.stopPollingService(getActivityContext(), TimerService.class, TimerService.ACTION);
                    try {
                        PushInterface.logout();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 清空信息
                    AppCache.setUser(null);
                    AppCache.setOrder(null);
                    AppCache.setStationOpenInfoBean(null);
                    UserBean bean = stationResult.getResult();
                    AppCache.setUser(bean);
                    Intent intent = new Intent();
                    intent.setClass(getActivityContext(), com.shouhuobao.take.MainActivity.class);
                    startActivity(intent);
                    for (Activity activity : ActivityMgr.getAllActivitys()) {
                        if (!(activity instanceof com.shouhuobao.take.MainActivity)) {
                            activity.finish();
                        }
                    }
                    Intents.startLauncherActivity(getActivityContext());
                } else {
                    showToast(stationResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }

    }

    private void handleSettingInfo(ReqResult<SettingBean> result) {
        //
        setting = result.getResult();
        if (setting != null) {
            ObjectSerialize.write(setting, null);
        } else {
            return;
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            // 战队中心
            case R.id.team_center_tv:
                startActivity(CourierTeamCenterActivity.class);
                break;
            //我的二维码
            case R.id.my_qr_code_tv:
                startActivity(CourierQRCodeActivity.class);
                break;
            //揽收任务
            case R.id.take_task_tv:
                startActivity(ServicePointActivity.class);
                break;
            //我的业绩
            case R.id.myenterprise_TV:
                intent = new Intent(getActivityContext(), MyPerformanceActivity.class);
                startActivity(intent);
                break;
            //我的打印机
            case R.id.myprint_TV:
                intent = new Intent(getActivityContext(), BluetoothSettingActivity.class);
                intent.putExtra("from", 1);
                startActivity(intent);
                break;
            // 存储卡上的缓存
            case R.id.setting_clear_data:
                DialogMgr.showQuit(getActivityContext(), new Callback() {
                    public void onDialogDismiss() {
                        MainActivity.instance.startOrStopRefreshLocation(false);
                        MainActivity.instance.setCouirerReceiveOrderStatus();
                        PollingUtils.stopPollingService(getActivityContext(), TimerService.class, TimerService.ACTION);
                        try {
                            PushInterface.logout();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        showLoadingDialog("删除中");
                        new DataCleanManager().cleanApplicationData(getActivityContext(), Config.getMainDiar());
                        AppCache.setUser(null);
                        cancelLoadingDialog();
                        ActivityMgr.finishAll();
                        Intent intent = new Intent(getActivityContext(), SplashActivity.class);
                        startActivity(intent);
                    }
                });
                break;
            //我的钱包
            case R.id.my_wallet_ll:
                if (bean == null) {
                    return;
                }
                intent = new Intent(getActivityContext(), MyWalletActivity.class);
                intent.putExtra("money", bean.getMoney());
                startActivity(intent);
                break;
            //历史任务
            case R.id.history_task_TV:
                intent = new Intent(getActivityContext(), TaskHistoryActivity.class);
                startActivity(intent);
                break;
            //切换至火箭联盟
            case R.id.switch_take:
                showLoadingDialog(null);
                AppHttp.getInstance().switchTake();
                break;
            //卫星仓
            case R.id.satellite_warehouse_tv:
                intent = new Intent(getActivityContext(), TaskSatelliteWarehouseActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 切换火箭联盟未申请开通时请求的数据
     */
    public void switchToAvenger() {
        showLoadingDialog(null);
        AppHttp.getInstance().openTheStation();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isRequestGet) {
            AppHttp.getInstance().getCourierCenterData();
        }
        isRequestGet = false;
        mhandler.removeMessages(1);
        mhandler.sendEmptyMessageDelayed(1, 1000 * 10);// 10秒钟内只查询一次
    }

    @Override
    public void onStop() {
        super.onStop();
        isRequestGet = true;
    }

    @Override
    public void onDestroy() {
        mhandler.removeMessages(1);
        super.onDestroy();
    }
}
